#region License
/*
The MIT License

Copyright (c) 2008 Sky Morey

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.IO;
using System.Collections;
namespace Capture.Utility
{
    /// <summary>
    /// Fifo Stream
    /// </summary>
    public class FifoStream : Stream
    {
        private const int BlockSize = 65536;
        private const int MaxBlocksInCache = (3 * 1024 * 1024) / BlockSize;
        private int _size;
        private int _readPosition;
        private int _writePosition;
        private Stack _usedBlocks = new Stack();
        private ArrayList _blocks = new ArrayList();

        private byte[] AllocBlock()
        {
            return (_usedBlocks.Count > 0 ? (byte[])_usedBlocks.Pop() : new byte[BlockSize]);
        }

        private void FreeBlock(byte[] block)
        {
            if (_usedBlocks.Count < MaxBlocksInCache)
                _usedBlocks.Push(block);
        }

        private byte[] GetWriteBlock()
        {
            byte[] result;
            if ((_writePosition < BlockSize) && (_blocks.Count > 0))
                result = (byte[])_blocks[_blocks.Count - 1];
            else
            {
                result = AllocBlock();
                _blocks.Add(result);
                _writePosition = 0;
            }
            return result;
        }

        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanSeek
        {
            get { return false; }
        }

        public override bool CanWrite
        {
            get { return true; }
        }

        public override long Length
        {
            get { lock (this) return _size; }
        }

        public override long Position
        {
            get { throw new NotSupportedException(); }
            set { throw new NotSupportedException(); }
        }

        public override void Close()
        {
            Flush();
        }

        public override void Flush()
        {
            lock (this)
            {
                foreach (byte[] block in _blocks)
                    FreeBlock(block);
                _blocks.Clear();
                _readPosition = 0;
                _writePosition = 0;
                _size = 0;
            }
        }

        public override void SetLength(long value)
        {
            throw new NotSupportedException();
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotSupportedException();
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            lock (this)
            {
                int value = Peek(buffer, offset, count);
                Advance(value);
                return value;
            }
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            lock (this)
            {
                int index = count;
                while (index > 0)
                {
                    int writeLength = Math.Min(BlockSize - _writePosition, index);
                    Array.Copy(buffer, offset + count - index, GetWriteBlock(), _writePosition, writeLength);
                    _writePosition += writeLength;
                    index -= writeLength;
                }
                _size += count;
            }
        }

        public int Advance(int count)
        {
            lock (this)
            {
                int sizeLeft = count;
                while ((sizeLeft > 0) && (_size > 0))
                {
                    if (_readPosition == BlockSize)
                    {
                        _readPosition = 0;
                        FreeBlock((byte[])_blocks[0]);
                        _blocks.RemoveAt(0);
                    }
                    int toFeed = (_blocks.Count == 1 ? Math.Min(_writePosition - _readPosition, sizeLeft) : Math.Min(BlockSize - _readPosition, sizeLeft));
                    _readPosition += toFeed;
                    sizeLeft -= toFeed;
                    _size -= toFeed;
                }
                return count - sizeLeft;
            }
        }

        public int Peek(byte[] buffer, int offset, int count)
        {
            lock (this)
            {
                int sizeLeft = count;
                int tempBlockPosition = _readPosition;
                int tempSize = _size;
                //
                int currentBlock = 0;
                while ((sizeLeft > 0) && (tempSize > 0))
                {
                    if (tempBlockPosition == BlockSize)
                    {
                        tempBlockPosition = 0;
                        currentBlock++;
                    }
                    int upper = (currentBlock < _blocks.Count - 1 ? BlockSize : _writePosition);
                    int toFeed = Math.Min(upper - tempBlockPosition, sizeLeft);
                    Array.Copy((byte[])_blocks[currentBlock], tempBlockPosition, buffer, offset + count - sizeLeft, toFeed);
                    sizeLeft -= toFeed;
                    tempBlockPosition += toFeed;
                    tempSize -= toFeed;
                }
                return count - sizeLeft;
            }
        }
    }
}
